import logging
import os
import datetime
from utils.yaml_util import read_config_yaml

current_date = datetime.date.today()
current_path = os.path.dirname(__file__)
log_name = read_config_yaml('log', 'log_name') + str(current_date) + ".log"
log_file_path = os.path.join(current_path, '../log/',log_name)


class LoggerUtil:
    def __init__(self):
        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(logging.INFO)


    def get_logger(self):
        self.create_console_log()
        self.create_file_log()
        return self.logger


    def create_console_log(self):
        if not any(isinstance(handler,logging.StreamHandler) for handler in self.logger.handlers):
            self.console_handler = logging.StreamHandler()
            console_log_level = read_config_yaml('log', "console_log_level")
            log_level_mapping = {
                'debug': logging.DEBUG,
                'info': logging.INFO,
                'warning': logging.WARNING,
                'error': logging.ERROR,
                'critical': logging.CRITICAL
            }
            if console_log_level in log_level_mapping:
                self.console_handler.setLevel(log_level_mapping[console_log_level])
            else:
                self.console_handler.setLevel(logging.INFO)
            console_log_format = read_config_yaml('log', 'console_log_format')
            if console_log_format:
                console_format = logging.Formatter(console_log_format)
                self.console_handler.setFormatter(console_format)
            self.logger.addHandler(self.console_handler)

    def create_file_log(self):
        if not any(isinstance(handler, logging.FileHandler) for handler in self.logger.handlers):
            self.file_handler = logging.FileHandler(str(log_file_path), "a", encoding="utf-8")
            file_log_level = read_config_yaml('log', 'file_log_level')
            log_level_mapping = {
                'debug': logging.DEBUG,
                'info': logging.INFO,
                'warning': logging.WARNING,
                'error': logging.ERROR,
                'critical': logging.CRITICAL
            }
            if file_log_level in log_level_mapping:
                self.file_handler.setLevel(log_level_mapping[file_log_level])
            else:
                self.file_handler.setLevel(logging.INFO)
            file_log_format = read_config_yaml('log', 'file_log_format')
            if file_log_format:
                file_format = logging.Formatter(file_log_format)
                self.file_handler.setFormatter(file_format)
            self.logger.addHandler(self.file_handler)
